Ext.define('CA.dictionary.TreeData', {
    extend: 'Ext.Panel',
    xtype: 'CA.dictionary.TreeData',

    leafCls: 'c-icon-kdb_form',

    initComponent: function(){
        var dic = this.dictionary,
            data = dic.data,
            meta = dic.meta,
            code = data.code,
            field = data.field,
            fields = [field, 'count'],
            customEditors = [],
            source = {},
            root = {
                expanded: true,
                selected: true
            };

        root[field] = 'Справочник';

        var columns = [
            {
                text: 'Код',
                dataIndex: 'id',
                align: 'right',
                sortable: false,
                renderer: function(val){
                    if(val == 'root') return '';
                    return '<span style="color:gray;padding-right:5px;">' + val + '</span>';
                },
                width: 40
            },
            {
                xtype: 'treecolumn',
                text: 'Наименование',
                sortable: false,
                dataIndex: field,
                flex: 1
            }
        ];

        Ext.each(meta, function(field){
            customEditors[field.code] = this.createPropery(field);
            source[field.code] = field.def || '';
        }, this);

        Ext.apply(this, {
            layout: 'border',
            items: [
                {
                    xtype: 'treepanel',
                    region: 'center',
                    style: 'border-right:1px solid #99BCE8',
                    flex: 3,
                    itemId: 'tree',
                    useArrows: true,
                    rootVisible: true,
                    border: false,
                    columns: columns,
                    root: root,
                    viewConfig: {
                        loadMask: false,
                        plugins: {
                            ptype: 'treeviewdragdrop',
                            ddGroup: 'dicTree',
                            dragText : 'выбрана {0} запись',
                            appendOnly: true
                        },
                        listeners: {
                            scope: this,
                            beforedrop: this.onBeforeDropNode,
                            drop: this.onDropNode
                        }
                    },
                    store: {
                        xtype: 'Ext.data.TreeStore',
                        fields: fields,
                        nodeParam: 'node',
                        proxy: {
                            paramOrder: ['node','dicCode'],
                            extraParams: { dicCode: code },
                            type: 'direct',
                            directFn: TreeDictionary.read,
                            reader: {
                                type:'json',
                                root: 'data'
                            }
                        },
                        listeners: {
                            scope: this,
                            load: function(tree, node, records){
                                Ext.each(records, function(node){
                                    if(!node.raw.count){
                                        this.leafNode(node);
                                    }
                                }, this);
                            }
                        },
                        sorters: [{
                            property: 'count',
                            direction: 'DESC'
                        }]
                    },
                    listeners: {
                        scope: this,
                        selectionchange: this.onSelectionChange
                    }
                },
                {
                    xtype: 'propertygrid',
                    region: 'east',
                    flex: 2,
                    itemId: 'dataSource',
                    closable: true,
                    closeAction: 'hide',
                    iconCls: this.leafCls,
                    hidden: true,
                    split: true,
                    border: false,
                    style: 'border-left:1px solid #99BCE8',
                    customEditors: customEditors,
                    source: source,
                    bbar: [
                        {
                            text: 'Cохранить',
                            scope: this,
                            handler: this.onGridSave
                        }
                    ],
                    listeners: {
                        scope: this,
                        close: function(){
                            var tree = this.down('#tree');

                            tree.getSelectionModel().deselectAll();
                        }
                    }
                }
            ]
        });

        this.callParent();
    },

    createPropery: function(field){
        return { xtype: 'textfield'};
    },

    createSource: function(data){
        var fields = this.dictionary.meta,
            source = {};

        data = data || {};

        Ext.each(fields, function(field){
            source[field.code] = data[field.code] || field.def || '';
        }, this);

        return source;
    },

    onSelectionChange: function(sm, selected){
        var ds = this.down('#dataSource'),
            data = this.dictionary.data,
            node = selected[0];

        if(!node){
            return;
        }

        if(node.isRoot()){
            ds.hide();
        } else {
            ds.show();
            ds.openType = 'update';
            ds.setTitle(node.get(data.field));
            ds.setSource(this.createSource(node.data));
        }
    },

    leafNode: function(node){
        node.collapse();
        node.set('expandable', false);
        node.set('iconCls', this.leafCls);
    },

    onBeforeDropNode: function(el, data, overModel){
        var node = data.records[0],
            parent = node.parentNode,
            allowDrop = parent !== overModel,
            isLeaf = parent.childNodes.length == 1;

        if(allowDrop && isLeaf){
            this.leafNode(parent);
        }

        return allowDrop;
    },

    onDropNode:  function(el, data, overModel){
        var node = data.records[0],
            folder = 'x-tree-icon-parent',
            code = this.dictionary.data.code,
            id = node.data.id,
            pid = overModel.data.id;

        overModel.set('expandable', true);
        overModel.set('iconCls', folder);

        TreeDictionary.move(id, pid, code);
    },

    createRecord: function(){
        var ds = this.down('#dataSource');

        ds.show();
        ds.openType = 'create';
        ds.setTitle('Новая запись');
        ds.setSource(this.createSource());
    },

    onGridSave: function(){
        var ds = this.down('#dataSource'),
            tree = this.down('#tree'),
            sm = tree.getSelectionModel(),
            node = sm.selected.items.length ? sm.selected.items[0] : tree.getRootNode(),
            code = this.dictionary.data.code,
            el = this.getEl(),
            data = ds.getSource(),
            action = TreeDictionary[ds.openType],
            dicData = this.dictionary.data;

        el.mask('Загрузка...');

        action(node.data.id, code, data, function(resp){
            el.unmask();

            if(ds.openType == 'update'){
                node.set(resp.data);
                ds.setTitle(resp.data[dicData.field]);
            } else {
                node.set('leaf', false);
                node.set('expandable', true);
                node.set('iconCls', 'x-tree-icon-parent');
                ds.setSource(this.createSource());

                node.expand(false, function(){
                    var newNode = node.findChild('id', resp.data.id) || node.appendChild(resp.data);

                    this.leafNode(newNode);
                }, this);
            }
        }, this);
    },

    removeSelected: function(){
        var ds = this.down('#dataSource'),
            tree = this.down('#tree'),
            sm = tree.getSelectionModel(),
            node = sm.selected.items.length ? sm.selected.items[0] : tree.getRootNode(),
            pNode = node.parentNode,
            code = this.dictionary.data.code;

        if(node.isRoot()){
            CA.error('Нельзя удалить корневой узел.');
            return;
        }

        CA.checkRemove('Удалить выбранную запись?', function(){
            TreeDictionary.remove(node.data.id, pNode.data.id, code, function(resp){
                if(CA.checkResponse(resp)){
                    node.remove(true);
                    ds.hide();

                    if(!pNode.childNodes.length){
                        this.leafNode(pNode);
                    }
                }
            }, this);
        }, this);
    }
});